<template>
  <ContentWrap>
    <el-row>
      <el-col>
        <div class="mb-2 float-right">
          <el-button size="small" type="primary" @click="showJson">生成JSON</el-button>
          <el-button size="small" type="success" @click="showOption">生成Options</el-button>
          <el-button size="small" type="danger" @click="showTemplate">生成组件</el-button>
          <el-button size="small" type="danger" @click="submitForm">保存</el-button>
        </div>
      </el-col>
      <el-col>
        <!-- 表单设计器 -->
        <fc-designer ref="designer" height="780px" />
      </el-col>
    </el-row>
    <!-- 弹窗 -->
    <Dialog :title="dialogTitle" v-model="dialogVisible" maxHeight="600">
      <div ref="editor" v-if="dialogVisible">
        <XTextButton style="float: right" :title="t('common.copy')" @click="copy(formValue)" />
        <el-scrollbar height="580">
          <pre>
            {{ formValue }}
          </pre>
        </el-scrollbar>
      </div>
      <span style="color: red" v-if="err">输入内容格式有误!</span>
    </Dialog>
  </ContentWrap>
</template>
<script setup lang="ts" name="CmsFormEditor">
// import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { useClipboard } from '@vueuse/core'
import { encodeConf, encodeFields, setConfAndFields } from '@/utils/formCreate'
// import { encodeConf, encodeFields } from '@/utils/formCreate'
import { FormVO } from '@/api/cms/model/types'
import * as ModelApi from '@/api/cms/model'
// import uniqueId from '@form-create/utils/lib/unique'
import FcDesigner from '@form-create/designer'
const { t } = useI18n() // 国际化
const message = useMessage() // 消息
const { query } = useRoute() // 路由

const designer = ref() // 表单设计器

const dialogVisible = ref(false) // 弹窗是否展示
const dialogLoading = ref(false) // 弹窗的加载中
const formValues = ref({
  id: query.id as unknown as number,
  enableJson: {
    conf: '',
    fields: []
  }
})
// 提交保存表单
const submitForm = async () => {
  // 提交请求
  dialogLoading.value = true
  try {
    const data = formValues.value as FormVO

    data.enableJson.conf = encodeConf(designer) // 表单配置
    data.enableJson.fields = encodeFields(designer) // 表单字段
    console.log('getOption->', designer.value.getOption())
    console.log('getRule->', designer.value.getRule())

    await ModelApi.updateFormApi(data)
    message.success(t('common.updateSuccess'))
    dialogVisible.value = false
  } finally {
    dialogLoading.value = false
  }
}

//更改表单设计器配置
// let updateUrl = import.meta.env.VITE_UPLOAD_URL
const designerSet = () => {
  //移除部分项目，后续迭代支持
  designer.value.removeMenuItem('el-transfer')
  designer.value.removeMenuItem('cascader')
  designer.value.removeMenuItem('tree')
  designer.value.removeMenuItem('slider')
  designer.value.removeMenuItem('el-button')
}

const dialogTitle = ref('')
const err = ref(false)
const type = ref(-1)
const formValue = ref('')

const openModel = (title: string) => {
  dialogVisible.value = true
  dialogTitle.value = title
}

const showJson = () => {
  openModel('生成JSON')
  type.value = 0
  formValue.value = designer.value.getRule()
}
const showOption = () => {
  openModel('生成Options')
  type.value = 1
  formValue.value = designer.value.getOption()
}

const showTemplate = () => {
  openModel('生成组件')
  type.value = 2
  formValue.value = makeTemplate()
}

/** 复制 **/
const copy = async (text: string) => {
  const { copy, copied, isSupported } = useClipboard({ source: text })
  if (!isSupported) {
    message.error(t('common.copyError'))
  } else {
    await copy()
    if (unref(copied)) {
      message.success(t('common.copySuccess'))
    }
  }
}

const makeTemplate = () => {
  const rule = designer.value.getRule()
  const opt = designer.value.getOption()
  return `<template>
  <form-create
    v-model="fapi"
    :rule="rule"
    :option="option"
    @submit="onSubmit"
  ></form-create>
</template>
<script setup lang=ts>
  import formCreate from "@form-create/element-ui";
  const faps = ref(null)
  const rule = ref('')
  const option = ref('')
  const init = () => {
    rule.value = formCreate.parseJson('${formCreate.toJson(rule).replaceAll('\\', '\\\\')}')
    option.value = formCreate.parseJson('${JSON.stringify(opt)}')
  }
  const onSubmit = (formData) => {
    //todo 提交表单
  }
  init()
<\/script>`
}
// ========== 初始化 ==========
//表单设计器设置 去除多余菜单项
onBeforeMount(() => {})

onMounted(() => {
  designerSet()

  const id = query.id as unknown as number
  if (!id) {
    return
  }
  //修改表单字段提交
  ModelApi.getFormApi(id).then((data) => {
    if (data.enableJson) {
      const fieldJson = JSON.parse(data.enableJson)
      setConfAndFields(designer, fieldJson.conf, fieldJson.fields)
      console.log('designer rule', designer.value.getRule())
    }
  })
})
</script>
